import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart' as dio;
import 'package:http_parser/http_parser.dart';
import 'package:merchants/models/review.dart';
import 'package:merchants/models/spu.dart';
import 'package:merchants/models/spu_list_response.dart';
import 'package:merchants/enum/spu_status.dart';
import 'package:merchants/services/base-service.dart';

class SpuService extends BaseService {
  SpuService({required super.ref});

  // 简单查询（GET）- 适用于基础过滤
  Future<SpuListResponse> getList({
    String? status,
    String? keyword,
    String? category,
    int page = 1,
    int pageSize = 20,
  }) async {
    final queryParams = <String, dynamic>{
      'page': page.toString(),
      'pageSize': pageSize.toString(),
    };
    
    if (status != null) queryParams['status'] = status;
    if (keyword != null) queryParams['keyword'] = keyword;
    if (category != null) queryParams['category'] = category;

    final response = await get<Map<String, dynamic>>(
      '/admin/spu/get-list',
      queryParams: queryParams,
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '获取商品列表失败');
        }
        return json;
      },
    );
    
    return SpuListResponse.fromJson(response['data'] as Map<String, dynamic>);
  }

  // 复杂查询（POST）- 适用于多条件过滤和排序
  Future<SpuListResponse> getListAdvanced({
    Map<String, dynamic>? filters,
    Map<String, dynamic>? sort,
    int page = 1,
    int pageSize = 20,
  }) async {
    final body = <String, dynamic>{
      'page': page,
      'pageSize': pageSize,
    };
    
    if (filters != null) body['filters'] = filters;
    if (sort != null) body['sort'] = sort;

    final response = await post<Map<String, dynamic>>(
      '/admin/spu/get-list',
      body: body,
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '获取商品列表失败');
        }
        return json;
      },
    );
    
    return SpuListResponse.fromJson(response['data'] as Map<String, dynamic>);
  }

  Future<void> updateSpu(Spu spu) async {
    await put<void>(
      '/admin/spu/${spu.id}',
      body: spu.toJson(),
      parser: (json) {}, // 无需返回值
    );
  }

  Future<List<Review>> fetchReviews() async {
    return await get<List<Review>>(
      '/comments',
      parser: (json) {
        // 假设 /comments 返回的是一个列表，而不是 { code, data } 格式
        // 如果实际响应是 { code, data } 格式，需要调整
        final List<dynamic> data = json['data'] ?? json;
        return data
            .map((json) => Review.fromJson(json as Map<String, dynamic>))
            .toList();
      },
    );
  }

  Future<String> createSpu(Spu spu) async {
    return await post<String>(
      '/admin/spu/create',
      body: {'data': spu.toJson()},
      parser: (json) {
        if (json['data'] == null || json['data']['id'] == null) {
          throw ApiException('Failed to create SPU: missing data.id');
        }
        return json['data']['id'] as String;
      },
    );
  }

  // 根据ID获取单个SPU
  Future<Spu> getSpuById(String id) async {
    final response = await get<Map<String, dynamic>>(
      '/admin/spu/$id',
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '获取商品详情失败');
        }
        return json;
      },
    );
    
    return Spu.fromJson(response['data'] as Map<String, dynamic>);
  }

  Future<void> deleteSpu(String id) async {
    await delete<void>(
      '/admin/spu/$id',
      parser: (json) {}, // 无需返回值
    );
  }

  Future<String> createSpuWithImages({
    required String name,
    required String category,
    required String description,
    required SpuStatus status,
    required List<Map<String, dynamic>> skus,
    required List<File> images,
  }) async {
    // 准备表单字段
    final fields = {
      'name': name,
      'category': category,
      'description': description,
      'status': status.toString().split('.').last,
      'skus': jsonEncode(skus),
    };

    // 准备文件
    final files = <dio.MultipartFile>[];
    for (var i = 0; i < images.length; i++) {
      final file = images[i];
      final ext = file.path.split('.').last.toLowerCase();

      // 计算 mime
      final mime =
          ext == 'jpg' || ext == 'jpeg'
              ? 'image/jpeg'
              : ext == 'png'
              ? 'image/png'
              : ext == 'gif'
              ? 'image/gif'
              : 'application/octet-stream';

      // 使用 Dio 的 MultipartFile.fromFile
      files.add(
        await dio.MultipartFile.fromFile(
          file.path, // ← 第一个参数必须是文件路径
          filename: 'image_$i.$ext', // 自定义文件名
          contentType: MediaType.parse(mime), // 指定 Content-Type
        ),
      );
    }

    // 使用 multipartPost 方法
    return await multipartPost<String>(
      '/admin/spu/create',
      fields: fields,
      files: files,
      parser: (json) {
        if (json['id'] == null) {
          throw ApiException('Failed to create SPU with images: missing id');
        }
        return json['id'] as String? ?? 'success';
      },
    );
  }
}
